package leetcode.hot100;
import datastruct.tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution102 {
    /**
     * 按 层序遍历 得到的节点值
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();
        if(root==null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            ArrayList<Integer> curLevelVals = new ArrayList<>();
            int curLevelSize = queue.size(); //这里很妙，每次遍历前队列里就是本层节点个数
            for (int i = 0; i < curLevelSize; i++) {
                //把当前层的节点数值先存入curLevelVals再存入res
                TreeNode curNode = queue.poll();
                curLevelVals.add(curNode.val);
                //把下一层的节点存储nextLevel
                if(curNode.left!=null) queue.offer(curNode.left);
                if(curNode.right!=null) queue.offer(curNode.right);
            }
            res.add(curLevelVals);
        }
        return res;
    }
}
